<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('周报') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item :label="$t('记录日期(周)')" prop="date">
        <DatePicker
          v-model="queryParams.date"
          type="week"
          format="yyyy 第WW周"
          :placeholder="$t('记录日期(周)')"
        />
      </el-form-item>
      <el-form-item :label="$t('项目名称')" prop="dealName">
        <el-input
          v-model="queryParams.dealName"
          :placeholder="$t('项目名称')"
          clearable
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item :label="$t('录入人')" prop="createName">
        <el-input
          v-model="queryParams.createName"
          :placeholder="$t('录入人')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('记录日期')">
        <DatePicker
          v-model="dateRange"
          type="daterange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['anxin:weekly:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t("新增") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['anxin:weekly:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportHandle"
        >{{ $t("导出") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['anxin:weekly:edit']"
          type="success"
          icon="el-icon-notebook-1"
          size="mini"
          @click="supplement"
        >{{ $t('补录') }}</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      tooltip-effect="darkTable"
      :data="anxinWeeklyList"
      :span-method="objectSpanMethod"
      border
      class="noneHoverBg anxinWeeklyList"
    >
      <el-table-column :label="$t('周期')" prop="yearWeek" show-overflow-tooltip width="150">
        <template slot-scope="scope">
          {{ $t('{year}年 第{week}周', { year: (scope.row.yearWeek + '').substring(0, 4), week: (scope.row.yearWeek + '').substring(4, 6)}) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('录入人')" prop="createBy.nickName" />
      <el-table-column :label="$t('记录日期')" prop="recordDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('项目名称')" prop="dealName" show-overflow-tooltip />
      <el-table-column :label="$t('时长(小时)')" prop="duration" width="100" />
      <el-table-column :label="$t('工作完成情况')" prop="workCompletion" show-overflow-tooltip>
        <template slot-scope="scope">
          <p class="pre">{{ scope.row.workCompletion }}</p>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" width="140">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['anxin:weekly:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="updateHandle(scope.row)"
          >{{ $t('修改') }}</el-button>
          <el-button
            v-hasPermi="['anxin:weekly:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改周报对话框 -->
    <el-dialog :title="$t('周报')" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <anxinWeeklyForm ref="anxinWeeklyForm" />
    </el-dialog>
  </div>
</template>

<script>
import { listAnxinWeekly, delWeekly, checkWeekly } from '@/api/anxin/weekly/anxinWeekly'
import anxinWeeklyForm from './anxinWeeklyForm.vue'
import { downLoadExcel } from '@/utils/excelDownload'
export default {
    components: {
        anxinWeeklyForm
    },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 总条数
          total: 0,
          // 周报表格数据
          anxinWeeklyList: [],
          // 是否显示弹出层
          formOpen: false,
        // 是否驻场字典
        siteOptions: [],
          // 查询参数
          queryParams: {
              dealName: undefined,
              date: undefined,
              yearWeek: undefined,
              createName: undefined,
              pageNum: 1,
              pageSize: 10
          },
          // 记录日期范围
          dateRange: [],
          // 表单参数
          form: {},
          // 表单校验
          rules: {
          }
      }
  },
  created() {
      this.getList()
      this.getDicts('sys_yes_no').then(response => {
          this.siteOptions = response.data
      })
  },
  methods: {
    /** 查询周报列表 */
    getList() {
        this.loading = true
        if (this.queryParams.date) {
          this.queryParams.yearWeek = this.getWeek(this.queryParams.date)
        } else {
          this.queryParams.yearWeek = undefined
        }
        listAnxinWeekly(this.addDateRange(this.queryParams, this.dateRange)
        ).then(response => {
            this.anxinWeeklyList = response.rows
            this.total = response.total
            this.loading = false
        })
    },
    // 是否驻场字典翻译
    siteFormat(row) {
      return this.selectDictLabel(this.siteOptions, row.site)
    },

    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            recordDate: undefined,
            dealId: undefined,
            duration: undefined,
            site: '0',
            workCompletion: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.dateRange = []
        this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
      const yearWeek = this.getWeek(new Date())
      if (yearWeek) {
        checkWeekly(yearWeek).then(response => {
          if (response.data) {
            this.formOpen = true
            this.$nextTick(() => {
              this.$refs.anxinWeeklyForm.init(null)
            })
          } else {
            this.$message({
              message: yearWeek.substring(0, 4) + this.$t('年 第') + yearWeek.substring(4, 6) + this.$t('周,周报已填写'),
              type: 'warning'
            })
          }
        })
      }
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        const data = {
          id: row.id,
          yearWeek: row.yearWeek,
          createBy: row.createBy.id
        }
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.anxinWeeklyForm.init(data)
        })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return delWeekly(row.yearWeek)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
      if (this.queryParams.date) {
        this.queryParams.yearWeek = this.getWeek(this.queryParams.date)
      } else {
        this.queryParams.yearWeek = undefined
      }
      downLoadExcel('/weekly/anxinWeekly/export', this.addDateRange(this.queryParams, this.dateRange))
    },
    // 导出弹出层关闭
    exportCancel() {
      this.exportOpen = false
      this.dateRange = []
      this.resetForm('exportQueryParams')
    },
    // 获取日期d是哪一年的第几周
    getWeek(d) {
      // 截掉时分秒保留整数天
      var date = new Date((d || new Date()))
      // 设置日期为当前周周四
      date.setDate(date.getDate() + (4 - (date.getDay() || 7)))
      var year = date.getFullYear()

      var firstDate = new Date(year, 0, 1)

      firstDate.setDate(firstDate.getDate() + (4 - (firstDate.getDay() || 7)))
      // 当年第一天早于周四第一周延后七天
      if (firstDate.getFullYear() < year) {
        firstDate.setDate(firstDate.getDate() + 7)
      }
      // 计算当前周和第一周之间周数差
      var week = Math.ceil(((date - firstDate) / 86400000 + 1) / 7)
      return year + '' + ('0' + week).substr(-2)
    },
    objectSpanMethod({ rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 2) {
        const spanArr = this.rowspan()
        for (let i = 0; i < spanArr.length; i++) {
          const _row = spanArr[rowIndex]
          return {
            rowspan: _row,
            colspan: 1
          }
        }
      }
      if (columnIndex === 1 || columnIndex === 6) {
        const spanArr = this.rowspan()
        for (let i = 0; i < spanArr.length; i++) {
          const _row = spanArr[rowIndex]
          return {
            rowspan: _row,
            colspan: 1
          }
        }
      }
    },
    rowspan() {
      // 二维数组，用于存放单元格合并规则
      const spanArr = []
      // 用于存储相同项的开始index
      let position = 0
      this.anxinWeeklyList.forEach((item, index) => {
        if (index === 0) {
          spanArr.push(1)
          position = 0
        } else {
          if (this.anxinWeeklyList[index].createBy.id === this.anxinWeeklyList[index - 1].createBy.id &&
          this.anxinWeeklyList[index].yearWeek === this.anxinWeeklyList[index - 1].yearWeek &&
          this.anxinWeeklyList[index].recordDate === this.anxinWeeklyList[index - 1].recordDate
          ) {
            spanArr[position] += 1 // 有相同项
            spanArr.push(0) // 名称相同后往数组里面加一项0
          } else {
            spanArr.push(1) // 同列的前后两行单元格不相同
            position = index
          }
        }
      })
      return spanArr
    },
    // 补录
    supplement() {
      if (this.queryParams.date) {
        if (this.getWeek(this.queryParams.date) >= this.getWeek(new Date())) {
          this.$message({
            message: this.$t('补录日期不能大于等于当前周'),
            type: 'warning'
          })
        } else {
          const yearWeek = this.getWeek(this.queryParams.date)
          checkWeekly(yearWeek).then(response => {
            if (response.data) {
              this.formOpen = true
              const data = {
                yearWeek: yearWeek,
                date: this.queryParams.date
              }
              this.$nextTick(() => {
                this.$refs.anxinWeeklyForm.init(data)
              })
            } else {
              this.$message({
                message: yearWeek.substring(0, 4) + this.$t('年 第') + yearWeek.substring(4, 6) + this.$t('周,周报已填写'),
                type: 'warning'
              })
            }
          })
        }
      } else {
        this.$message({
          message: this.$t('请选择记录日期'),
          type: 'warning'
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
 .pre {
    white-space: pre-line !important;
    word-break: break-all;
    word-wrap: break-word;
    text-align:left;
    line-height: 18px;
}
</style>

